package com.kkb.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping("upload.do")
    public String upload(@RequestParam("myFile") MultipartFile myFile, HttpServletRequest request){
        //获取原始文件名称
        String fileName = myFile.getOriginalFilename();
        System.out.println(fileName);
        // 实际开发中，一般都要将文件重新名称进行存储
        // 存储到服务器的文件名称=随机的字符串+根据实际名称获取到源文件的后缀
        String file = UUID.randomUUID().toString().replace("-","")+fileName.substring(fileName.lastIndexOf("."));
        System.out.println(file);
        System.out.println(UUID.randomUUID().toString().length());

        //文件存放路径
        String filePath = request.getServletContext().getRealPath("/uploadFile")+"\\";

        try {
            myFile.transferTo(new File(filePath+file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文件上传成功！"+filePath+file);

        return "ok";

    }

    @RequestMapping("hello.do")
    public String file(){
        return "fileHandle";
    }

    @RequestMapping("img.do")
    public String img(){
        return "download";
    }


    @RequestMapping("download.do")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
        //指定文件的路径--保证指定路径下有文件
        String path = request.getServletContext().getRealPath("\\uploadFile")+"\\kkk.jpg";
        //创建响应头信息
        HttpHeaders headers = new HttpHeaders();
        //标记以流的方式作出响应
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //以附件的形式响应给用户
        headers.setContentDispositionFormData("hhh", URLEncoder.encode("kkk.jpg","utf-8"));
        File file = new File(path);

        ResponseEntity<byte[]> resp = new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);

        return resp;

    }


}
